import React, { useCallback, useContext, useEffect } from 'react';
// import PropTypes from 'prop-types';
import Taro from '@tarojs/taro';
import { Image } from '@tarojs/components';
import { context } from './group';
/**
 @name 图片预览
 * */
function ImagePreview(props) {
  const { src, onClick } = props;
  const { isPreviewGroup, previewUrls, setPreviewUrls } = useContext(context);

  useEffect(() => {
    setPreviewUrls(listUrls => {
      if (isPreviewGroup && listUrls.indexOf(src) < 0) {
        listUrls.push(src);
        return listUrls;
      }
      return listUrls;
    });
  }, [src]);

  const onPreview = useCallback(() => {
    // todo 本地的图片是无法预览的
    if (isPreviewGroup) {
      Taro.previewImage({
        current: props.src,
        urls: previewUrls,
      });
    } else {
      Taro.previewImage({
        current: props.src,
        urls: [props.src],
      });
    }
    if (onClick) {
      onClick();
    }
  }, [isPreviewGroup, previewUrls]);

  return <Image {...props} onClick={onPreview} />;
}

ImagePreview.defaultProps = {};

ImagePreview.propTypes = {};

export default ImagePreview;
